package com.service.yzj.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.service.yzj.dao.COrderMapper;
import com.service.yzj.dao.CProductMapper;
import com.service.yzj.dao.CustomMapper;
import com.service.yzj.dto.boss.CustomListRequest;
import com.service.yzj.dto.boss.OrderListRequest;
import com.service.yzj.model.custom.CustomAddressInfo;
import com.service.yzj.model.custom.CustomUserInfo;
import com.service.yzj.model.order.OrderAppointment;
import com.service.yzj.model.order.OrderAppointmentDetail;
import com.service.yzj.model.order.OrderDetail;
import com.service.yzj.model.order.OrderLog;
import com.service.yzj.model.pages.boss.CustomDetailPage;
import com.service.yzj.model.pages.boss.CustomListItem;
import com.service.yzj.model.pages.boss.CustomListPage;
import com.service.yzj.model.pages.boss.OrderDetailPage;
import com.service.yzj.model.pages.boss.OrderListPage;
import com.service.yzj.model.user.Employee;

@Service
public class BossServiceImpl implements BossService {
  private final CProductMapper cProductMapper;
  private final COrderMapper cOrderMapper;
  private final CustomMapper customMapper;
  private Logger logger;

  
  public BossServiceImpl(@Autowired CProductMapper cProductMapper, @Autowired COrderMapper cOrderMapper, @Autowired CustomMapper customMapper) {
    this.cProductMapper = cProductMapper;
    this.cOrderMapper = cOrderMapper;
    this.customMapper = customMapper;
    this.logger = LoggerFactory.getLogger(WxServiceImpl.class);
  }

  /**
   * 根据查询条件获取客户列表
   */
  @Override
  public CustomListPage getCustomers(CustomListRequest request) {
    int pageNumber = request.getPageNumber();
    int pageSize = request.getPageSize();
    int offset = (pageNumber - 1) * pageSize;
    String name = request.getName();
    String telephone = request.getTelephone();
    String residentialQuarter = request.getResidentialQuarter();
    String server = request.getServer();
    String square = request.getSquare();
    String type = request.getType();


    List<CustomListItem> pageList = new ArrayList<>();
    List<CustomUserInfo> users = customMapper.getCustomInfoWithKeyword(offset, pageSize, name, telephone, residentialQuarter, server, square, type);
    for (CustomUserInfo user : users) {
      List<OrderDetail> orderDetails= cOrderMapper.getOrderListWithUser(user.getId());
      List<String> orders = new ArrayList<>();
      long orderId = orderDetails.get(0).getId();
      OrderAppointmentDetail appointment = cOrderMapper.getAppointmentDetailWithOrderId(orderId);
      for (OrderDetail detail : orderDetails) {
        orders.add(detail.getDescription());
      }

      CustomListItem customListItem = new CustomListItem(user, orders, appointment);
      pageList.add(customListItem);
    }


    int pageTotal = customMapper.getCustomInfoWithKeywordTotalCount(offset, pageSize, name, telephone, residentialQuarter, server, square, type);
    CustomListPage customListPage = new CustomListPage(pageList, pageNumber, pageSize, pageTotal);
    return customListPage;
  }

  /**
   * 根据客户id获取客户详情
   */
  @Override
  public CustomDetailPage getCustomerById(long userId) {
    CustomUserInfo user = customMapper.getCustomerById(userId);
    // 根据用户id获取订单列表，取订单中正在服务的订单的且有预约信息的订单)
    List<OrderDetail> orders = cOrderMapper.getOrderListWithUser(userId);
    long orderId = getOrderIdByUserIdWithInServiceAppointment(orders, userId);

    // 组装预约数据
    OrderAppointment appointment = null;
    if(orderId != 0){
      // 查询预约信息
      appointment = getAppointmentByOrderId(orderId);
    }
    // 组装客户详细信息
    CustomDetailPage customDetailPage = new CustomDetailPage(user, orders, appointment);
    return customDetailPage;
  }

  /**
   * 根据订单id获取预约信息
   * @param orderId
   * @return
   */
  public OrderAppointment getAppointmentByOrderId(long orderId) {
    OrderAppointmentDetail appointmentDetail = cOrderMapper.getAppointmentDetailWithOrderId(orderId);
    long addressId = appointmentDetail.getAddressId();
    CustomAddressInfo address = cOrderMapper.getAddressById(addressId);
    long employeeId = appointmentDetail.getEmployeeId();
    Employee worker = cOrderMapper.getWorkerWithId(employeeId);
    return new OrderAppointment(appointmentDetail, address, worker);
  }

  // 根据userId获取订单列表，取订单中正在服务的订单的且有预约信息的订单orderNo
  public long getOrderIdByUserIdWithInServiceAppointment(List<OrderDetail> orders, long userId) {
    // 优先查看是否存在已预约的订单
    for (OrderDetail order : orders) {
      if (order.getStatus() == 2) {
        return order.getId();
      }
    }
    // 如果没有已预约的订单，则查看是否存在正在服务的订单
    for (OrderDetail order : orders) {
      if (order.getStatus() > 2 && order.getStatus() < 10) {
        return order.getId();
      }
    }
    return 0;
  }

  /**
   * 根据客户所有订单的状态，获取客户类别
   * @param orders
   * @return
   */
  public String getCustomType(List<OrderDetail> orders){
    int orderStatus = 0;
    for (OrderDetail order : orders) {
      // * 订单状态：1-未预约 2-已预约 3-已测量 4-设计中 5-已报价 6-已签单 7-施工中 8-验收中 9-已验收 10-已结算
      int status = order.getStatus();
      if (status > 1 && status < 10) {
        orderStatus = 1;
        break;
      } else if (status == 10) {
        orderStatus = 2;
      }
    }

    switch (orderStatus) {
      case 0:
        // 意向客户：无服务中的订单，无历史订单
        return "intend";
      case 1:
        // 正式客户：有服务中的订单
        return "formal";
      case 2:
        // 历史客户：无服务中的订单，有历史订单
        return "historical";
      default:
        return "intend";
    }
  }

  @Override
  public List<OrderDetail> getOrderListByUserId(long userId) {
    return null;
  }
  /**
   * 根据查询条件获取订单列表
   */
  @Override
  public OrderListPage getOrderList(OrderListRequest request) {
    int pageNumber = request.getPageNumber();
    int pageSize = request.getPageSize();
    int offset = (pageNumber - 1) * pageSize;
    String orderNo = request.getOrderNo();
    String customName = request.getCustomName();
    String residentialQuarter = request.getCustomResidentialQuarter();
    String square = request.getCustomSquare();
    String telephone = request.getCustomTelephone();
    String server = request.getServer();

    List<OrderDetail> orders = cOrderMapper.getOrderListWithKeywords(offset, pageSize, orderNo, customName, telephone, residentialQuarter, square, server);

    OrderListPage page = new OrderListPage(orders, pageNumber, pageSize, 0);
    return page;
  }

  /**
   * 根据订单id获取订单详情
   */
  @Override
  public OrderDetailPage getOrderById(long orderId) {

    // 根据订单id查询订单对应的客户详情
    CustomUserInfo user = customMapper.getCustomerByOrderId(orderId);
    // 根据订单id查询订单详情
    OrderDetail orderDetail = cOrderMapper.getOrderDetailById(orderId);
    // 根据订单id查询订单日志
    List<OrderLog> logs = cOrderMapper.getOrderLogsByOrderId(orderId);
    
    // 查询预约数据
    OrderAppointment appointment = getAppointmentByOrderId(orderId);


    OrderDetailPage page = new OrderDetailPage();
    page.setUser(user);
    page.setOrderDetail(orderDetail);
    page.setOrderLogs(logs);
    page.setAppointment(appointment);

    return page;
  }
}


